package com.lk;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 *Condition.await /signal/signalAll
 * 等同于
 *    Thread.wait /notify/notifyAll
 *
 */
public class TestProducerConsumerLock {
    public static void main(String[] args) {
        ClerkLock clerk = new ClerkLock();
        ProducerLock producer = new ProducerLock(clerk);
        ConsumerLock consumer = new ConsumerLock(clerk);
        new Thread(producer).start();
        new Thread(consumer).start();
    }
}

class ClerkLock{
    int num=0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    public void get(){
        lock.lock();
        try {
            while(num>=1){
                System.out.println("库存已满");
                try {
                    Thread.sleep(400);
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName()+" : " + ++num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public void sale(){
        lock.lock();
        try {
            while(num<=0){
                System.out.println("没有库存");
                try {
                    Thread.sleep(400);
                    condition.await();
                } catch (InterruptedException e) {
                }
            }
            System.out.println(Thread.currentThread().getName()+ " : " + --num);
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}

class ProducerLock implements Runnable{

    private ClerkLock clerk;

    public ProducerLock(ClerkLock clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++) {
            clerk.get();
        }
    }
}

class ConsumerLock implements Runnable{
    private ClerkLock clerk;

    public ConsumerLock(ClerkLock clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        for(int i=0;i<20;i++){
            clerk.sale();
        }
    }
}
